package com.hyd.tweet.xmpp;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.PresenceShow;
import com.google.appengine.api.xmpp.SendResponse;
import com.hyd.tweet.AppException;
import com.hyd.tweet.Application;
import com.hyd.tweet.util.StringUtils;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 发送 GTalk 消息
 *
 * @author yiding.he
 */
public class XMPPMessageSender {

    private static final Logger logger =
            Logger.getLogger(XMPPMessageSender.class.getName());

    /**
     * 发送 GTalk 消息。如果 messages 的元素都为空则不会发送。
     *
     * @param receiverJID 接收人
     * @param messages    消息（可能是多条）
     */
    public static void sendMessages(JID receiverJID, List<String> messages) {
        if (messages == null) {
            return;
        }

        JID senderJID = new JID(receiverJID.getId().split("@")[0] + "@" + Application.getAppChatDomain());

        StringBuilder sb = new StringBuilder();

        for (String message : messages) {
            if (!StringUtils.isEmpty(message)) {
                sb.append(message).append("\n\n");
            }
        }

        if (sb.length() > 0) {
            sendMessageText(senderJID, receiverJID, sb.toString().trim());
        }
    }

    /**
     * 发送单条 GTalk 消息
     *
     * @param senderJID   发送人
     * @param receiverJID 接收人
     * @param message     消息内容
     */
    private static void sendMessageText(JID senderJID, JID receiverJID, String message) {

        try {
            Message msg = new MessageBuilder()
                    .withFromJid(senderJID)
                    .withRecipientJids(receiverJID)
                    .withBody(message)
                    .build();

            SendResponse response = XMPPUtils.getXMPP().sendMessage(msg);

            SendResponse.Status status = response.getStatusMap().get(receiverJID);
            if (status != null && status != SendResponse.Status.SUCCESS) {
                throw new AppException("Error sending message to " + receiverJID + ": " + status);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "通过" + senderJID + "发送消息给" + receiverJID + "失败", e);
        }
    }

    /**
     * 检查用户当前能否接收消息
     *
     * @param jid 要检查的帐号
     *
     * @return 如果用户能接收消息则返回 true
     */
    public static boolean isAvailable(JID jid) {
        try {
            PresenceShow presenceShow = XMPPUtils.getXMPP().getPresence(jid).getPresenceShow();
            return presenceShow == PresenceShow.CHAT ||
                    presenceShow == PresenceShow.NONE || 
                    presenceShow == null;
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
            return false;
        }
    }
}
